﻿using System;
using System.Collections.Generic;
using System.Text;
using ColdSun.Commons.Entities;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using ColdSun.Commons;
using System.IO;
using System.Reflection;
using ColdSun.Commons.Configs;
using ColdSun.Framework;

namespace ColdSun.Services
{
    public class ServiceDeskUserService
    {
        public string GenerateServiceDeskUser(string originalExcelFile, string replaceWordFile, List<ColdSun.Commons.Entities.Replacement> replacementInfos, DateTime reportDate, string replaceFinalFile, string replaceFinalFolder)
        {
            Microsoft.Office.Interop.Word.Application wordObj = null;
            Microsoft.Office.Interop.Excel.Application replaceExcelApplication = null;
            Microsoft.Office.Interop.Excel.Workbook replaceWorkBook = null;
            Sheets replaceSheets = null;
            Worksheet replaceWorksheet = null;
            Document templateDoc = null;
            try
            {
                if (!File.Exists(originalExcelFile))
                {
                    Logger.Info(string.Format("Can't find file {0} ", originalExcelFile));
                    return string.Format("Can't find file {0} ", originalExcelFile);
                }

                if (!File.Exists(replaceWordFile))
                {
                    Logger.Info(string.Format("Can't find file {0} ", replaceWordFile));
                    return string.Format("Can't find file {0} ", replaceWordFile);
                }

                if (!Directory.Exists(replaceFinalFolder))
                {
                    Logger.Info(string.Format("Can't find folder {0} ", replaceFinalFolder));
                    return string.Format("Can't find folder {0} ", replaceFinalFolder);
                }

                if (string.IsNullOrEmpty(replaceFinalFile))
                {
                    Logger.Info(string.Format("Final file name {0} is empty", replaceFinalFile));
                    return string.Format("Final file name {0} is empty", replaceFinalFile);
                }

                object replaceWordTemplateFile = Utilities.GetFullFileName(replaceWordFile);
                object missing = Missing.Value;
                wordObj = new Microsoft.Office.Interop.Word.Application();
                wordObj.Visible = false;

                templateDoc = new Document();
                templateDoc = wordObj.Documents.Open(ref replaceWordTemplateFile);
                string saveFileName = string.Format("{0}\\{1}", replaceFinalFolder, replaceFinalFile)
                   .Replace("#Date#", DateTime.Now.ToString(CommonConfigs.ExportDateTimeFormatInFileName + " hhmmss"));
                object saveWordFileName = saveFileName;
                templateDoc.SaveAs(ref saveWordFileName);
                Logger.Info(string.Format("Save as to file {0}", saveFileName));

                replaceExcelApplication = new Microsoft.Office.Interop.Excel.Application();
                replaceWorkBook = replaceExcelApplication.Workbooks.Open(originalExcelFile);
                replaceSheets = replaceWorkBook.Worksheets;
                object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                Microsoft.Office.Interop.Word.Find findObject = wordObj.Selection.Find;

                foreach (ColdSun.Commons.Entities.Replacement replacementInfo in replacementInfos)
                {
                    replaceWorksheet = (Worksheet)replaceSheets[replacementInfo.SheetName];
                    foreach (ReplacementDetail detail in replacementInfo.Details)
                    {
                        findObject.Text = detail.ReplaceParam;
                        findObject.Wrap = WdFindWrap.wdFindContinue;  

                        if (!string.IsNullOrEmpty(detail.Range))
                        {
                            replaceWorksheet.Range[detail.Range].Copy();
                            findObject.Execute();
                            findObject.Replacement.Application.Selection.Paste();
                            findObject.Replacement.Text = ""; ;
                            findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing, ref missing, ref missing,
                                ref replaceAll, ref missing, ref missing, ref missing, ref missing);
                        }
                        else
                        {
                            string replaceValue = string.Format("{0}", replaceWorksheet.get_Range(Utilities.Cell(detail.ColumnName, detail.RowIndex.Value)).Value);
                            findObject.Replacement.Text = replaceValue;
                            findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing, ref missing, ref missing,
                                ref replaceAll, ref missing, ref missing, ref missing, ref missing);
                        }
                    }
                }

                findObject.Text = "#dd#";
                findObject.Wrap = WdFindWrap.wdFindContinue;  
                findObject.Replacement.Text = reportDate.ToString("dd");
                findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);

                findObject.Text = "#MM#";
                findObject.Wrap = WdFindWrap.wdFindContinue;  
                findObject.Replacement.Text = reportDate.ToString("MM");
                findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);

                findObject.Text = "#yyyy#";
                findObject.Wrap = WdFindWrap.wdFindContinue;  
                findObject.Replacement.Text = reportDate.ToString("yyyy");
                findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);

                findObject.Text = "#Date#";
                findObject.Wrap = WdFindWrap.wdFindContinue;  
                findObject.Replacement.Text = reportDate.ToString("dd/MM/yyyy");
                findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);

                replaceWorksheet.Range["A1"].Copy();
                templateDoc.Save();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return string.Format("{0}\r\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                if (templateDoc != null)
                {
                    templateDoc.Close();
                }

                if (wordObj != null)
                {
                    wordObj.Quit();
                    ReleaseComObjectService.ReleaseComObject(wordObj);
                }

                ReleaseComObjectService.ReleaseComObject(replaceWorksheet);
                ReleaseComObjectService.ReleaseComObject(replaceSheets);
                ReleaseComObjectService.ReleaseWorkbookObject(replaceWorkBook, false);
                ReleaseComObjectService.ReleaseExcelApplicationObject(replaceExcelApplication);

                GC.Collect();
                GC.WaitForPendingFinalizers();

            }
            return "Successful";
        }
    }
}
